<template>
  <div class="advice" title="地图反馈/聊天">
    <svg @click="adviceDialog" width="80" height="80" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">
      <!-- 聊天框背景 -->
      <rect x="12" y="12" width="40" height="40" rx="4" fill="#e3f2fd" opacity="0.8">
        <animate attributeName="opacity" values="0.8;0.9;0.8" dur="3s" repeatCount="indefinite"/>
      </rect>
      
      <!-- 主聊天框 -->
      <path d="M16 16H48V36H32L24 42V36H16V16Z" fill="#4a6fa5">
        <animate attributeName="fill" values="#4a6fa5;#3a5a8f;#4a6fa5" dur="4s" repeatCount="indefinite"/>
      </path>
      
      <!-- 消息气泡1 -->
      <rect x="20" y="20" width="24" height="8" rx="4" fill="white">
        <animate attributeName="height" values="8;6;8" dur="2s" repeatCount="indefinite"/>
      </rect>
      
      <!-- 消息气泡2 -->
      <rect x="20" y="32" width="16" height="8" rx="4" fill="white" opacity="0.8">
        <animate attributeName="width" values="16;18;16" dur="2.5s" repeatCount="indefinite" begin="0.5s"/>
      </rect>
      
      <!-- 输入框 -->
      <rect x="16" y="48" width="32" height="6" rx="3" fill="white" opacity="0.6">
        <animate attributeName="opacity" values="0.6;0.9;0.6" dur="2s" repeatCount="indefinite"/>
      </rect>
      
      <!-- 右上角小气泡 -->
      <circle cx="54" cy="14" r="10" fill="#ff7043">
        <animate attributeName="r" values="4;5;4" dur="1.5s" repeatCount="indefinite"/>
        <animate attributeName="cy" values="14;13;14" dur="1.5s" repeatCount="indefinite"/>
      </circle>
      
      <!-- 小气泡数字1 -->
      <text x="54" y="16" font-family="Arial" font-size="8" fill="white" text-anchor="middle" font-weight="bold">
        {{
          messages.length
        }}
        <animate attributeName="opacity" values="1;0.5;1" dur="1.5s" repeatCount="indefinite"/>
      </text>
      
      <!-- 脉冲动画 -->
      <circle cx="32" cy="32" r="0" stroke="#4a6fa5" stroke-width="1" fill="none" opacity="0">
        <animate attributeName="r" values="0;20;0" dur="3s" repeatCount="indefinite"/>
        <animate attributeName="opacity" values="0;0.3;0" dur="3s" repeatCount="indefinite"/>
      </circle>
    </svg>
    <Dialog
      v-model:visible="visible"
      :title="title"
      @close="() => moneyDialog(false)"
    >
      <div class="chat-container">
        <div class="chat-messages" ref="messagesContainer">
          <div 
            v-for="(message, index) in messages"
            :key="message.id"
            class="message"
          >
            <span>{{ message.province }}网友：</span>
            <div
              class="received"
            >
              <div class="message-content">{{ message.content }}</div>
              <div class="message-time">{{ formatDate(message.created_time) }} 发表</div>
            </div>
            <div class="status-icons">
              <div :class="['status-icon', iconHandle(message.status)]" :title="message.status_text">
              </div>
            </div>
          </div>
          <div class="typing-indicator" v-if="isTyping">
            {{ typingUser }} 正在输入...
          </div>
        </div>
        <div class="chat-input-area">
          <textarea 
            v-model="newMessage" 
            @keydown.enter.exact.prevent="sendMessage" 
            class="chat-input" 
            placeholder="输入消息..."
          ></textarea>
          <button 
            @click="sendMessage" 
            class="send-button"
            :disabled="!newMessage"
          >
            发送
          </button>
        </div>
      </div>
    </Dialog>
  </div>
</template>
<script setup>
import Dialog from '../dialog/index.vue';
import { ref, onMounted, nextTick } from 'vue';
const title = ref('地图反馈/建议');
const visible = ref(false);
const adviceDialog = (status = true) => {
  visible.value = status
  if (status) {
    getAdvice();
  }
}
const formatDate = (time) => {
  const date = new Date(time);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
}
const getAdvice = async() => {
	const res = await fetch(`http://1.95.157.217/api/map/getAdvice`, {
		method: 'GET'
	}).then(response => {
		if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
		}
		return response.json();
})
	if (res.code === 0) {
		messages.value = res.data;
	}
}
const sendAdvice = async() => {
	const res = await fetch('http://1.95.157.217/api/map/sendAdvice', {
		method: 'POST',
    body: JSON.stringify({
      content: newMessage.value
    }),
    headers: {
      'Content-Type': 'application/json'
    }
	}).then(response => {
		if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
		}
    return response.json();
	})
  if (res.code === 0) {
    getAdvice();
  }
}
const iconHandle = item => {
  switch(item) {
    case 1:
      return 'accept';
    case 2:
      return 'reject';
    default:
      return 'unread'
  }
}
const statusHandle = item => {
  switch(item) {
    case 1:
      return '已接受建议';
    case 2:
      return '拒绝该提议';
    default:
      return 'unread'
  }
}
const messages = ref([]);
const newMessage = ref('');
const isTyping = ref(false);
const typingUser = ref('');
const messagesContainer = ref(null);

const sendMessage = () => {
  if (!newMessage.value.trim()) return;
  sendAdvice()
  newMessage.value = '';
  scrollToBottom();
};

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

const formatTime = (date) => {
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};

onMounted(() => {
  getAdvice();
  scrollToBottom();
});
</script>
<style scoped>
.advice {
  position: fixed;
  right: 10px;
  bottom: 10%;
  cursor: pointer;
}
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 600px;
}
.chat-header {
  background-color: #4a6fa5;
  color: white;
  padding: 15px 20px;
  font-size: 18px;
  font-weight: bold;
}
.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 15px;
}
.message {
  display: flex;
  align-items: flex-start;
}
.message span {
  white-space: nowrap;
}
.message .sent {
  align-self: flex-end;
  background-color: #4a6fa5;
  color: white;
  border-bottom-right-radius: 5px;
  padding: 12px 15px;
  border-radius: 18px;
  line-height: 1.4;
  position: relative;
  word-wrap: break-word;
}
.message .received {
  padding: 10px;
  align-self: flex-start;
  background-color: #e5e5ea;
  color: black;
  border-bottom-left-radius: 5px;
}
.message-time {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.7);
  margin-top: 5px;
  text-align: right;
  color: rgba(0, 0, 0, 0.5);
}
.message-content {
  word-break: break-all; /* 在恰当的断字点进行换行 */
  overflow: hidden; /* 超出范围隐藏 */
  text-overflow: ellipsis; /* 文字超出用省略号 */
  display: -webkit-box; /* 盒子模型 */
  -webkit-line-clamp: 4; /* 显示的文本行数 */
  -webkit-box-orient: vertical; 
}
.chat-input-area {
  display: flex;
  padding: 15px;
  border-top: 1px solid #e5e5ea;
  background-color: #f9f9f9;
  align-items: flex-end;
}
.chat-input {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
  font-size: 16px;
  resize: none;
  height: 50px;
  max-height: 150px;
}
.send-button {
  margin-left: 10px;
  padding: 0 20px;
  background-color: #4a6fa5;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.2s;
  height: 35px;
}
.send-button:hover {
  background-color: #3a5a8f;
}
.send-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
.typing-indicator {
  padding: 5px 15px;
  font-size: 14px;
  color: #666;
  font-style: italic;
}
.status-icons {
  display: flex;
  align-self: flex-end;
}

.status-icon {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-left: 5px;
  position: relative;
  cursor: pointer;
  transition: all 0.3s ease;
}

/* 接受图标 - 绿色对勾 */
.accept {
  background-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.3);
}

.accept::before, .accept::after {
  content: '';
  position: absolute;
  background-color: white;
  transform-origin: left center;
}

.accept::before {
  width: 7px;
  height: 2px;
  left: 6px;
  top: 12px;
  transform: rotate(45deg);
}

.accept::after {
  width: 12px;
  height: 2px;
  left: 8px;
  top: 14px;
  transform: rotate(-45deg);
}

/* 拒绝图标 - 红色叉号 */
.reject {
  background-color: #F44336;
  box-shadow: 0 0 0 2px rgba(244, 67, 54, 0.3);
}

.reject::before, .reject::after {
  content: '';
  position: absolute;
  background-color: white;
  width: 12px;
  height: 2px;
  left: 6px;
  top: 11px;
}

.reject::before {
  transform: rotate(45deg);
}

.reject::after {
  transform: rotate(-45deg);
}

/* 未读图标 - 蓝色圆点 */
.unread {
  background-color: #e5e5ea;
  box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.3);
  animation: pulse 1.5s infinite;
}

/* 脉冲动画 */
@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(33, 150, 243, 0.4);
  }
  70% {
    transform: scale(1.05);
    box-shadow: 0 0 0 6px rgba(33, 150, 243, 0);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(33, 150, 243, 0);
  }
}

/* 悬停效果 */
.status-icon:hover {
  transform: scale(1.1);
}

/* 点击效果 */
.status-icon:active {
  transform: scale(0.95);
}
</style>